package com.emm.yixun.openapi.utils;

import java.util.Map;

import com.alibaba.fastjson.JSONObject;

/**
 * Created by john on 15/1/8.
 */
public class RSAUtil {
    private static String publicKey;
    private static String privateKey;

    static {
        try {
            Map<String, Object> keyMap = RSACoder.getKeyMap();
            publicKey = RSACoder.getPublicKey(keyMap);
            privateKey = RSACoder.getPrivateKey(keyMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 私钥解密
     *
     * @param data base64加密数据
     * @return
     * @throws Exception
     */
    public static String decryptByPrivateKeyBASE64(String data)
            throws Exception {
 /*   	 RSAPrivateKey prikey = RSACoder.loadPrivateKey(privateKey);
 	    byte[] encryptedData = RSACoder.getBASE64Decoder().decodeBuffer(data);
 	    byte[] bytes=RSACoder.decrypt(prikey,encryptedData);
         return new String(bytes);*/
         return subsectionDecryptByPrivateKeyBASE64(data);
    }


    /**
     * 公钥加密
     *
     * @param data      源数据
     * @return
     * @throws Exception
     */
    public static String encryptByPublicKeyBASE64(byte[] data)
            throws Exception {
    	/*RSAPublicKey pubkey = RSACoder.loadPublicKey(publicKey);
        byte[] encryptedData =RSACoder.encrypt(pubkey,data);
        return RSACoder.getBASE64Encoder().encode(encryptedData);*/
    	return subsectionEncryptByPublicKeyBASE64(data);
    }
    
    /**
     * 分段公钥加密
     *
     * @param data      源数据
     * @return
     * @throws Exception
     */
    private static String subsectionEncryptByPublicKeyBASE64(byte[] data)
            throws Exception {
        byte[] encryptedData = RSACoder.encryptByPublicKey(data, publicKey);
        return RSACoder.getBASE64Encoder().encode(encryptedData);
    }
    
    
    /**
     * 分段私钥解密
     *
     * @param data base64加密数据
     * @return
     * @throws Exception
     */
    private static String subsectionDecryptByPrivateKeyBASE64(String data)
            throws Exception {
        byte[] encryptedData = RSACoder.getBASE64Decoder().decodeBuffer(data);
        byte[] bytes = RSACoder.decryptByPrivateKey(encryptedData, privateKey);
        return new String(bytes);
    }


    
    public static void main(String[] args) {
    	JSONObject object=new JSONObject();
    	object.put("name", "张三");
    	object.put("age", 20);
    	object.put("phone", "18665716400");
		try { 
			//公钥加密
		    String result=subsectionEncryptByPublicKeyBASE64(object.toJSONString().getBytes());
		    System.out.println(result);
	    	//私钥解密
			System.out.println(subsectionDecryptByPrivateKeyBASE64(result));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
